/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    unordered_map<TreeNode*, long long> map;
    int dfs(TreeNode* root)
    {
        if (root == nullptr) return 0;
        long long tmp = root->val;
        if (root->left != nullptr)
        {
            tmp += dfs(root->left);
        }
        if (root->right != nullptr)
        {
            tmp += dfs(root->right);
        }
        map[root] = tmp;
        return tmp;
    }
    int maxProduct(TreeNode* root)
    {
        long long tmp = 0;
        dfs(root);
        for (auto& [ptr, sum] : map)
        {
            if (ptr == root) continue;
            tmp = max(tmp, (map[root] - map[ptr]) * map[ptr]);
        }

        return tmp % (1000000007);
    }
};